<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" width="800px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { formSchema } from './data';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import {Api, list, add, update } from './api';


export default defineComponent({
  name: 'OrderTypeDrawer',
  components: { BasicDrawer, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);

    const [registerForm, { resetFields, setFieldsValue, updateSchema, saveOrUpdate }] = useForm({
      rowKey: 'typeId',
      labelWidth: 100,
      saveApi: Api.add,
      updateApi: Api.update,
      schemas: formSchema,
      showActionButtonGroup: false,
      params:{
        state:1,
      },
      baseColProps: { lg: 24, md: 24 },
    });

    const [registerDrawer, { setDrawerProps,changeLoading, closeDrawer }] = useDrawerInner(async (data) => {
      await resetFields();
      setDrawerProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;

      if (isUpdate.value) {
        await setFieldsValue(data.record);
      }
      const treeData = await list();
      //上级菜单赋值
      await updateSchema({
        field: 'parentId',
        componentProps: { treeData },
      });
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增分类' : '编辑分类'));

    async function handleSubmit() {
      try {
        changeLoading(true);
        await saveOrUpdate(emit);
        closeDrawer();
      } finally {
        changeLoading(false);
      }
    }
    return { registerDrawer, registerForm, getTitle, handleSubmit };
  },
});
</script>
